package com.shmilyou.dissertationmanagement.utils;
/* Created with 岂止是一丝涟漪     530060499@qq.com    2019/2/10 */

import com.shmilyou.dissertationmanagement.tools.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebUtils {

    private static final Logger log = LoggerFactory.getLogger(WebUtils.class);

    /** 返回状态码200 */
    public static ResponseEntity<Map<String, Object>> success() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    public static ResponseEntity<Map<String, Object>> failure() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    public static ResponseEntity<Map<String, Object>> success(Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", data);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 保存上传的文件
     *
     * @return 保存的文件名或空字符串
     */
    public static String saveUploadFile(MultipartFile file, String savePath) {
        if (file != null && file.getSize() > 0) {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".doc".equals(fileType) || ".docx".equals(fileType) || ".pdf".equals(fileType) || ".png".equals(fileType) || 
                ".jpg".equals(fileType) || ".jpeg".equals(fileType) || ".xlsx".equals(fileType) || ".ppt".equals(fileType) || ".pptx".equals(fileType)) {
                try {
                    //save file
                    String saveName = Utils.generateDateNum() + "_" + fileName;
                    file.transferTo(new File(savePath + saveName));
                    return saveName;
                } catch (IOException e) {
                    log.error(e.getLocalizedMessage(), e);
                }
            }
        }
        return "";
    }

}
